import jenkins.model.Jenkins
import hudson.model.ListView
import hudson.model.Cause 
import hudson.model.Queue

/*
sql: 
create database jenkins;
use jenkins;
CREATE TABLE `job_msg` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `job_name` varchar(255) NOT NULL COMMENT 'job名称',
  `git_url` varchar(255) NOT NULL COMMENT '仓库地址',
  `job_type` varchar(50) NOT NULL COMMENT '项目语言类型',
  `job_port` varchar(20) NOT NULL DEFAULT '8090' COMMENT '项目的端口',
  `project_path` varchar(255) NOT NULL COMMENT '项目的制品路径',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8mb4;

*/


pipeline {
    agent any
    parameters {
        string(description: '项目名称，必须全部使用英文',     name: 'add_name', trim: true)
        string(description: '项目git仓库',  name: 'git_url', trim: true)
        choice(description: '项目类型',     name: 'job_type',choices: ['java', 'node'])
        choice(description: '项目平台',     name: 'job_view', choices: ['ruoyi', '其他'])
        string(description: '项目端口',     name: 'job_port', trim: true)
        string(description: '项目中文名',   name: 'job_cname', trim: true)
        string(description: '制品路径',     name: 'project_path', trim: true)
    }
    stages {
        stage('获取用户信息') {
            steps {
                script {
                    wrap([$class: 'BuildUser']){
                        env.BUILD_USER = "${env.BUILD_USER_ID}" // 当次构建的用户 拼音
                        env.BUILD_USER_FIRST_NAME = "${env.BUILD_USER_FIRST_NAME}" // 当次构建用户 中文名字
                        env.BUILD_USER_EMAIL = "${env.BUILD_USER_EMAIL}" // 当次构建用户 邮箱
                    }
                }
            }
        }
        stage('参数检测') {
            steps {
                script {
                    println "检查输入参数"
                    params.each { key, value ->
                        if (value == null || value.trim() == '') {
                            error "参数 ${key} 未输入"
                        }
                    }
                    println "检查参数合法性"
                    sh'''
                        [ -z `echo $add_name |awk '{print gensub(/[!-~]/,"","g",$0)}'`  ] || { echo "add_name项目名【${add_name}】中可能包含中文，请检查" ; exit 98 ;  }
                        [ -d  ${JENKINS_HOME}/jobs/${add_name} ]  && { echo "请检查项目名称是否重复！" ; exit 97 ; }
                        echo "$job_port" | grep -qE '^[0-9]+$'  || { echo "项目端口非数字！" ; exit 96 ; }
                        echo "$git_url" | grep -qE '^http://gitlab.zzz5.top/.*.git$'  || { echo "git地址不合法" ; exit 96 ; }
                    '''
                }

            }
        }
        stage('自动创建job') {
            steps {
                script {
                    def jobParams = [
                        add_name: env.add_name,
                        git_url: env.git_url,
                        job_type: env.job_type,
                        job_view: env.job_view,
                        job_port: env.job_port,
                        project_path: env.project_path
                    ]
                    println jobParams
                    insertDataToMysql(jobParams)
                    createCusJob(env.job_type,env.job_view, env.add_name,env.job_cname)
                    sleepForPipeline(15)
                    stopJobBuilds(env.add_name)
                }
            }
        }
    }
}


def createCusJob(jobType, view_name, jobName, jobCName) {

    def job_template="shareLibr/${jobType}_tmp"

    // copy项目
    def jenkins = Jenkins.getInstance()
    def sourceJob = jenkins.getItemByFullName(job_template)
    def targetJobName = jobName

    if (sourceJob != null) {
        def targetJob = jenkins.copy(sourceJob, targetJobName)
        targetJob.save()
        println("项目已成功复制为: ${targetJobName}")
    } else {
        println("未找到源项目")
    }

    // 禁用项目
    def job = Jenkins.instance.getItemByFullName(jobName)
    job.setDisabled(true)
    job.save()
    println("禁用项目")

    // 启用项目
    job.setDisabled(false)
    job.save()
    println("启用项目")

    // 将项目移动到某个视图中
    moveJobToView(view_name, job)
    
    // 修改备注
    job.setDescription("这是自动新增的job")
    job.save()
    println("修改job备注")

    // 修改job的显示名称
    job.setDisplayName("【${view_name}】-${jobType}-${jobCName}")
    job.save()
    println("修改job显示名称")

    // 立刻构建项目
    buildJobNow(job)
}

def buildJobNow(job) {
    def cause = new Cause.UserIdCause()
    job.scheduleBuild(0, cause)
}

def sleepForPipeline(seconds) {
    sleep time: seconds, unit: 'SECONDS'
}

def stopJobBuilds(jobName) {
    def job = Jenkins.instance.getItemByFullName(jobName)
    job.getBuildByNumber(1).delete()
}

def moveJobToView(viewName, job) {
    def jenkins = Jenkins.getInstance()
    def view = jenkins.getView(viewName)
    if (view == null) {
        // 如果视图不存在，创建新的视图
        view = new ListView(viewName)
        jenkins.addView(view)
        println("视图已创建: ${viewName}")
    }
    view.doAddJobToView(job.name)
    view.save()
}

def insertDataToMysql(Map pmap) {
    getDatabaseConnection(type: 'GLOBAL') {
        def result = sql("""INSERT INTO `job_msg` SET
            job_name=\"${pmap.add_name}\",
            git_url=\"${pmap.git_url}\",
            job_type=\"${pmap.job_type}\",
            job_port=\"${pmap.job_port}\",
            project_path=\"${pmap.project_path}\"
            ;""")
    }
}